from app.models.article_model import Article
from datetime import datetime

def create_article(title: str, content: str):
    """创建文章"""
    try:
        article = Article.create(
            title=title,
            content=content,
            created_at=datetime.now(),
            updated_at=datetime.now()
        )
        return article
    except Exception as e:
        print(f"创建文章失败: {e}")
        return None

def get_article_by_id(article_id: int):
    """通过ID获取文章"""
    try:
        return Article.get(Article.id == article_id)
    except Article.DoesNotExist:
        return None

def get_all_articles():
    """获取所有文章"""
    try:
        return Article.select().order_by(Article.created_at.desc())
    except Exception as e:
        print(f"获取文章列表失败: {e}")
        return None

def update_article(article_id: int, title: str, content: str):
    """更新文章"""
    try:
        article = Article.get(Article.id == article_id)
        article.title = title
        article.content = content
        article.updated_at = datetime.now()
        article.save()
        return article
    except Article.DoesNotExist:
        return None
    except Exception as e:
        print(f"更新文章失败: {e}")
        return None

def delete_article(article_id: int):
    """删除文章"""
    try:
        article = Article.get(Article.id == article_id)
        article.delete_instance()
        return True
    except Article.DoesNotExist:
        return False
    except Exception as e:
        print(f"删除文章失败: {e}")
        return False